package com.nutshare.lt.table;

import com.nutshare.lt.Stat;

import javax.swing.table.AbstractTableModel;
import java.util.*;

public class PopularTableModel extends AbstractTableModel
{

    public Stat stat;

    public PopularTableModel(Stat stat)
    {
        this.stat = stat;
    }


    public int getRowCount()
    {
        return stat.ltw.getCapacity();
    }

    public int getColumnCount()
    {
        int cols = stat.popularResults.size() * 2 + stat.popularResults.size();
        return cols;
    }

    public Object getValueAt(int rowIndex, int columnIndex)
    {

        // System.out.println("\n" + rowIndex + " " + columnIndex + " " + (columnIndex%3));

        int counter = -1;
        counter = getRealColumn(columnIndex);

        if(counter>-1)
        {
            //System.out.println("counter" + counter + ";" + stat.popularResults.size());

            TreeMap<Integer, Integer> r = getResultForRealColumnIndex(counter);
            // System.out.println(r);

            Object[] keysArray = r.keySet().toArray();
            Object[] valsArray = r.values().toArray();

            Integer key = (Integer) keysArray[rowIndex];
            Integer val = (Integer) valsArray[rowIndex];

            Integer ret;
            if ((columnIndex+2)%3 == 0)
            {
                ret = val;
            }
            else
            {
                ret = key;
            }


            return ret;
        }

        return null;
    }

    public TreeMap<Integer, Integer> getResultForRealColumnIndex(int counter)
    {
        return stat.popularResults.get(counter);
    }

    private int getCurrentColumnIndex(int columnIndex)
    {
        return getColumnCount() - columnIndex - 1;
    }

    public int getRealColumn(int columnIndex)
    {
        int counter = -1;
        int currentColumnIndex = getCurrentColumnIndex(columnIndex);



        if(columnIndex==0 || columnIndex%3 == 0)
        {
            // 0, 3, 6, ...
            counter = currentColumnIndex / 3;


        }
        else if((columnIndex+2)%3 == 0)
        {
            // 1, 4, 7, ...
            counter = (currentColumnIndex +2) / 3  - 1;
        }
        return counter;
    }
}
